package com.Adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.bolao.R;
import com.entidades.BetRow;

public class RowAdapter extends BaseAdapter{

    List<BetRow>data = null;
    private LayoutInflater mInflater;

    static class ViewHolder{
    	private Spinner spinner;
    	private TextView text;
    }
    

    
    public RowAdapter(Context mContext, List<BetRow> data) {

        this.data = data;
        mInflater = LayoutInflater.from(mContext);


    }
    
    public static void SelectSpinnerItemByValue(Spinner spnr, long value)
    {
        SpinnerAdapter adapter = (SpinnerAdapter) spnr.getAdapter();
        for (int position = 0; position < adapter.getCount(); position++)
        {
            if(adapter.getItemId(position) == value)
            {
                spnr.setSelection(position);
                return;
            }
        }
    }

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.row, null);
			holder = new ViewHolder(); 
			holder.spinner = (Spinner) convertView.findViewById(R.id.rowSpinner);
            holder.text = (TextView) convertView.findViewById(R.id.rowText);
            convertView.setTag(holder);
                  
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		BetRow betRow = data.get(position);

		holder.spinner.setAdapter(betRow.getAdapter());

		holder.text.setText(convertView.getContext().getResources().getIdentifier(betRow.getText(), 
				"string",  convertView.getContext().getPackageName()));  
		holder.spinner.setOnItemSelectedListener(new BetListener(betRow));
		
		if(betRow.getUserBet()!=-1){
			SelectSpinnerItemByValue(holder.spinner, betRow.getUserBet());
		}
		return convertView;
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int arg0) {
		return data.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}
	
	public class BetListener implements OnItemSelectedListener {

		private BetRow betRow;
		public BetListener(BetRow betRow){
			this.betRow = betRow;
		}
		
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
			betRow.setUserBet((int) parent.getItemIdAtPosition(pos));
			
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
		
	}

}
